import React from 'react'
// ===================================================================== Temp
import AddEditModal from '#cpt/temp/AddEditModal'
import Controls from '#cpt/temp/Controls'
import TableControls from '#cpt/temp/TableControls'
import DisposeModal from './cpt/dispose-modal'
import Confirm from '#cpt/temp/Confirm'
import Delete from '#cpt/temp/Delete'
// ===================================================================== Declare
const { $Lazy, $fn, $http } = window
// ===================================================================== Lazy
const Page 			= $Lazy.load(()=>import('#tp/page/page-container'))
const Tabs 			= $Lazy.load(()=>import('#tp/tabs/tabs'))
//
const $cache 	= $Lazy.file(()=>import('#private/cache-api'))
// const Upload 		= $Lazy.hook(()=>import('@antd/upload'))
// ===================================================================== data
const level = [
	{ name: '普通', value: '1' },
	{ name: '重要', value: '2' },
	{ name: '紧急', value: '3' },
	{ name: '重要且紧急', value: '4' }
]
const saveName = 'workbench-todo'
// ===================================================================== component
class Index extends React.Component{
	state = {
		index: $fn.local(saveName) || 0,
		formData : [
			{ label: '接收人',		name: 'to_user',	half:true, required: true, type:'treeSelect', cache:false, multiple:false, filterName: 'label', loading:true }, // 修复编辑接收人不显示 2022年11月7日17:36:05 敖得卓
			{ label: '级别',		name: 'level', 		half:true, required: true, type:'select', data:level },
			{ label: '待办类型',		name: 'event_type', half:true, required: true, type:'select' },
			{ label: '截止时间',		name: 'end_at', 	half:true, required: true, type:'date-time', before: Date.now() },
			{ label: '关联条码',		name: 'spec_code',	half:true, btn: { label: '关联', onClick: () => {
				const { spec_code } = this.formRef.getValue()
				$http.pull(this, 'work-event/getCode', { param: { spec_code }}).then(data => {
					if ($fn.isArray(data)) return
					const {spec_code: code, patient_name, age, sex, hosp_name, kind_names, coll_time} = data
					this.formRef.setValue({content:`\n———————————————————————\n条码: ${code}、姓名: ${patient_name || '--'}、年龄: ${age || '--'}、性别: ${sex || '--'}\n医院名称: ${hosp_name || '--'}\n项目名称: ${kind_names || '--'}\n采样时间: ${coll_time|| '--'}` })
				})
			} }},
			{ label: '标题',		name: 'title', 		full:true, required: true },
			{ label: '内容',		name: 'content',	full:true, required: true, type:'textarea'},
			{ label: '上传文件',	 name: 'url',	full:true, type:'upload', mode: 'button',  btnText: '上传文件', preview: true, fileType: ['img', 'pdf', 'word', 'excel']},
		],
		pages: [
			{ component:$Lazy.state(()=>import('./cpt/a')), controls: 1 },
			{ component:$Lazy.state(()=>import('./cpt/b')), controls: 1 },
			{ component:$Lazy.state(()=>import('./cpt/c')), controls: 1 },
			{ component:$Lazy.state(()=>import('./cpt/d')), controls: 0 },
			{ component:$Lazy.state(()=>import('./cpt/a1')), controls: 1 },
			{ component:$Lazy.state(()=>import('./cpt/b1')), controls: 1 },
			{ component:$Lazy.state(()=>import('./cpt/c1')), controls: 1 },
			{ component:$Lazy.state(()=>import('./cpt/d1')), controls: 0 },
		],
		forms : [
			{ label: '标题',			name: 'title' },
			{ label: '级别',			name: 'level',		type: 'select',	data: level },
			{ label: '创建时间',			name: 'date-range',	type: 'date-range', names: ['start_at','end_at'] },
			{ label: '待办类型',			name: 'event_type',	type: 'select' },
			{ label: '接收人',			name: 'to_user',	type: 'select' },
			{ label: '发起人',			name: 'from_user',	type: 'select' },
		]
	}
	
	componentDidMount(){
		const { pages, index } = this.state
		
		this.getSelect()
		
		pages[index].first = true
		this.setState({ pages })
		
		$fn.fresh.on(()=>{
			const { index } = this.state
			this['ref' + index].fetch()
		})
		
	}
	componentWillUnmount(){
		// $fn.remove(saveName)
		$fn.fresh.remove()
	}
	
	// 获取下拉数据
	getSelect = () => {
		const { forms, formData } = this.state
		
		$cache.then( async f => {
			// 待办列表 
			const data = await f.getCache({ api:'work-event/eventTypeSelect' })
			const uData = await f.getCache({ api:'employee' })
			$fn.setRow(forms, 'event_type', data)
			$fn.setRow(formData, 'event_type', data)
			// 联系人  employee/departmentuser
			$fn.setRow(formData, 'to_user',  await f.getCache({ api: 'work-group/groupSelect'})) // 待办分组api 2022年11月11日14:36:04 敖得卓
			// 用户
			$fn.setRow(forms, 'to_user', uData)
			$fn.setRow(forms, 'from_user', uData)
			this.setState({ forms, formData })
		})
	}
	
	tabs = [
		{ title:'我的发起', status:0 },
		{ title:'我的发起-处理中', status:1 },
		{ title:'我的发起-已完成', status:2 },
		{ title:'我的发起-已逾期', status:3 },
		{ title:'我的处理', status:4 },
		{ title:'我的处理-处理中', status:5 },
		{ title:'我的处理-已完成', status:6 },
		{ title:'我的处理-已逾期', status:7 },
	]
	
	colWith = [110, 130, 130, 0, 110, 130, 130, 0]
	
	cols  = controls => {
		const { index } = this.state
		let col = [
			{ title: '待办级别', 		dataIndex: 'level', 		width: 100, render: (text, {level_name})=>{
				const colors = [ '#2cc7ac', '#0F9BCF', '#F89D00', '#FF5656' ]
				return (
					<div className='fxm'>
						<i className='r100px mr10' style={{width:6,height:6, background: colors[ +text - 1] }}></i>
						<span>{level_name}</span>
					</div>
				)
			} },
			{ title: '待办标题', 		dataIndex: 'title', 			width:200 },
			{ title: '待办类型', 		dataIndex: 'event_type_name', 	width:140 },
			{ title: '发起部门', 		dataIndex: 'from_depart', 		width:140 },
			{ title: '发起人', 			dataIndex: 'from_user', 		width:140 },
			{ title: '发起时间', 		dataIndex: 'created_at', 		...$fn.table.time },
			{ title: '截至时间', 		dataIndex: 'end_at', 			...$fn.table.time },
			{ title: '接收部门', 		dataIndex: 'to_depart', 		width:140 },
			{ title: '接收人', 			dataIndex: 'to_user', 			width:140 }
		]
		if(controls) col = [...col, TableControls.controls.call(this, { width: this.colWith[index] })]
		return col
	}
	
	// 表格操作按钮
	table_controls = ({uuid, has_new_message, is_from},rows) => {
		return [
			+this.state.index === 0 && TableControls.edit.call(this, 'work-event/info', {uuid}, { click: ()=> $fn.disabledRows(this.state.formData, 'to_user', true) }),
			+this.state.index === 0 && this.onDel([uuid]),
			+this.state.index === 4 && TableControls.click.call(this, '进行处理', () => $http.submit(this, 'work-event/takeOk', { param: {uuids: [uuid]} }).then(() => window.refresh.onRefresh())),
			(+this.state.index === 1||+this.state.index === 5) && TableControls.click.call(this, null, () => $fn.pushTo(this, `detail?uuid=${uuid}&type=${+this.state.index === 1 ? '0' : '1'}&send=${+this.state.index === 1 ? '1' : '0'}`), { style: { borderColor: '#999', color: '#333' }, ghost: true, children: this.msgButton( +this.state.index === 1 ? '沟通' : '处理', has_new_message) }),
			+this.state.index === 1 && Confirm.call(this, '完成', 'work-event/finish', { idStr: 'uuids', param: [[uuid]], onOk: () => window.refresh.onRefresh() }),
			(+this.state.index === 2||+this.state.index === 6)&& TableControls.click.call(this, '详情', () => $fn.pushTo(this, `detail?uuid=${uuid}&type=0&send=${+this.state.index === 2 ? '1' : '0'}`)),
		]
	}
	
	onDel = uuid => Delete.call(this, 'work-event/delete', { uuid, idStr:'uuids', isKeys: !$fn.hasArray(uuid), onComplete:()=>this['ref' + this.state.index].fetch() })
	
	msgButton = (label, chatting) => <span className='todo'>{ +chatting ? <><span className='chatting'></span>{label + '中'}</> : label }</span> 
	
	// 操作按钮
	controls = () => [
		+this.state.index === 0 && Controls.add.call(this, { click: ()=> {
			const { formData } = this.state
			$fn.disabledRows(this.state.formData, 'to_user', false)
			this.setState({formData})
		} }),
		+this.state.index === 0 && this.onDel(this.ref0?.state?.selectedKeys),
		+this.state.index === 4 && Controls.click.call(this,'批量进行处理',()=> $http.submit(this, 'work-event/takeOk', { param: {uuids: this.ref4?.state?.selectedKeys} }).then(() => window.refresh.onRefresh()), { disabled: !$fn.hasArray(this.ref4?.state?.selectedKeys) }),
		+this.state.index === 5 && Controls.click.call(this,'批量处理',()=> {
			this.disposeModalRef.open(this.ref5?.state?.selectedRows, this.ref5?.state?.selectedKeys)
		}, { disabled: !$fn.hasArray(this.ref5?.state?.selectedKeys) }),
		+this.state.index === 1 && Confirm.call(this,'批量完成', 'work-event/finish', { idStr: 'uuids', param: [this.ref1?.state?.selectedKeys] ,disabled: !$fn.hasArray(this.ref1?.state?.selectedKeys), onOk: () => window.refresh.onRefresh()})
	]
	render(){
		const { index, pages, forms } = this.state
		return (
			<>
				<Page>
					{/* 选项卡 */}
					<Tabs
						defaultActiveKey = { index }
						data		= { this.tabs }
						onTabs 		= { (data, index) => {
							const _index = +index
							// pages[+index].first = true
							pages.forEach((v, i) => v.first = i === +index)
							$fn.local(saveName, index)
							this.setState({ index:_index, pages })
						}}
						controls	= { this.controls() }
					/>
					
					{
						pages.map((v,i)=> v.first && <div className='ex rel fv' key={i} style={{ display: +index === i && v.first ? 'flex' : 'none' }}>
							<v.component onRef={ref=>this['ref' + i] = ref} cols={this.cols(v.controls)} forms={forms} onKeyChange={ () => {this.setState({}) }} {...this.props} />
						</div>)
					}
				
				</Page>
				{/* 添加 */}
				{ AddEditModal.call(this,{ title:'待办', width: 800, api: 'work-event/add', editApi: 'work-event/edit', onRefresh:()=> this['ref' + index].fetch() }) }
				{/* 处理 */}
				<DisposeModal ref={ref => this.disposeModalRef = ref} />
			</>
		)
	}
}

export default Index